package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.ActivityModel;
import biznussoft.metercor.entity.ExpensesModel;
import biznussoft.metercor.listener.DialogListener;
import biznussoft.metercor.utils.CustomProgressDialog;
import biznussoft.metercor.utils.ExpandCollapseAnimation;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ExpensesMasterFragment extends Fragment implements OnClickListener{

	private DialogListener listener;
	private int mHeight3 = 0;
	private LinearLayout expensesLayout,newExpensesLayout;
	private RestClient client;
	private ActivityModel mobel;
	private CheckBox mBillable;
	private EditText etAmount,etDescription,etTransactionDate;
	private Dialog progressDialog;
	private String strId;
	private int position;
	private Spinner spType;
	private ImageView expenses,notes,save;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.expense_master_fragment, null);
	}


	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		listener = (DialogListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		client = MainActivity.mActivity.client;
		notes = (ImageView) getView().findViewById(R.id.Notes);
		notes.setOnClickListener(this);
		expenses = (ImageView) getView().findViewById(R.id.addExpenses);
		expensesLayout = (LinearLayout) getView().findViewById(R.id.sectionsLayout3);
		newExpensesLayout = (LinearLayout) getView().findViewById(R.id.lllayoutexpense_new_mode);
		save = (ImageView) getView().findViewById(R.id.save);
		save.setOnClickListener(this);
		spType = (Spinner) getView().findViewById(R.id.spExpenseType);
		etAmount = (EditText)getView().findViewById(R.id.etAmount);
		etDescription = (EditText)getView().findViewById(R.id.etDescription);
		etTransactionDate = (EditText) getView().findViewById(R.id.ettransactionDate);
		mBillable = (CheckBox) getView().findViewById(R.id.cbeditBillable);
		
		Bundle i = getArguments();
		progressDialog = CustomProgressDialog.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		position= i.getInt("Position");
		getDetails(position);                                                
		expenses.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				addExpenses();				
			}
		});
	}


	public void addExpenses() {
		expensesLayout.setVisibility(View.GONE);
		newExpensesLayout.setVisibility(View.VISIBLE);
	}



	public void getDetails(int position){
		mobel = ServiceOrderActivityRecordsFragment.list.get(position);
		Session.sFconnectActivity =mobel.getActivityName();
		strId = mobel.getId();
		getExpenses(strId);


	}

	public void getExpenses(String id){

		try{
			expensesLayout.setVisibility(View.VISIBLE);
			newExpensesLayout.setVisibility(View.GONE);

			String serviceOrder = "SELECT  Name,Id,Activity_Name__c,FConnect__Technician__c,FConnect__Expense_Type__c,FConnect__Amount__c,FConnect__Billable__c,FConnect__Discription__c,FConnect__Technician_Date__c,FConnect__Activity__c From FConnect__Expense__c where FConnect__Activity__c ="+"'"+id+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {    
						progressDialog.dismiss();
						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						ArrayList<ExpensesModel> expenseList = new ArrayList<ExpensesModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ExpensesModel bean = _gson.fromJson(jsonArray.getString(i), ExpensesModel.class);
								expenseList.add(bean);
							}
						}

						showRecords(expenseList);

					} catch (Exception e) {

						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  expenses is  :"+e.getMessage());
		}
	}
	public void showRecords(ArrayList<ExpensesModel> list) {
		for (int i = 0; i < list.size(); i++) {
			ExpensesModel donor = list.get(i);
			View view = getActivity().getLayoutInflater().inflate(R.layout.expenses_displaydata, expensesLayout,false);
			//View headerColor = (View)view.findViewById(R.id.title_graphic);
			//headerColor.setBackgroundResource(R.drawable.title_bar_orange);

			TextView	mName = (TextView) view.findViewById(R.id.tvContactLastName);
			TextView	mBgroup = (TextView) view.findViewById(R.id.tvContactTitle);
			TextView 	mAge = (TextView) view.findViewById(R.id.tvContactEmail);
			TextView 	mGender = (TextView) view.findViewById(R.id.tvContactPhone);

			mName.setText(donor.getName());
			mBgroup.setText(donor.getExpense());
			mAge.setText(donor.getAmount());
			mGender.setText(donor.getTechnicianDate());

			expensesLayout.addView(view);


			final ImageView iv_expandcollapse = (ImageView) view.findViewById(R.id.iv_CollapseExpand);
			final LinearLayout sectionitemsParent = (LinearLayout) view.findViewById(R.id.llSectionItems);
			iv_expandcollapse.setImageResource(R.drawable.expand);
			sectionitemsParent.setVisibility(View.GONE);


			iv_expandcollapse.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					if (sectionitemsParent.getVisibility() == View.VISIBLE) {// Collapse
						ExpandCollapseAnimation collapseAnimation = new ExpandCollapseAnimation(sectionitemsParent, 1000, 1, iv_expandcollapse);
						mHeight3 = collapseAnimation.getHeight();
						iv_expandcollapse.startAnimation(collapseAnimation);
					} else {// Expand
						ExpandCollapseAnimation expandAnimation = new ExpandCollapseAnimation(sectionitemsParent, 1000, 0, iv_expandcollapse);
						if (mHeight3 == 0) {
							mHeight3 = getSectionitemsHeight();
						}
						expandAnimation.setHeight(mHeight3);
						iv_expandcollapse.startAnimation(expandAnimation);
					}
				}

				private int getSectionitemsHeight() {
					return (int) (4 * getResources().getDimension(R.dimen.section_item_height));
				}
			});
		}

	}



	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.save:

			addExpensesTOSFDC();

			break;
		case R.id.Notes:
			Session.sStartTime = true;
			Session.sEndTime = false;
			Session.sActivity = false;
			Session.sTime = false;
			Session.sExpense = true;
			Session.sNewTime = false;
			Session.sNewExpenses = false;
			listener.nextDialog("date");

			break;

		default:
			break;
		}
	}
	
	public void setTransactionDate(String date){

		etTransactionDate.setText(date);
	}

	public void addExpensesTOSFDC(){


		progressDialog = CustomProgressDialog.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		boolean flag = mBillable.isChecked();

		String objectType = "FConnect__Expense__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Activity__c",strId);                  
		fields.put("FConnect__Technician__c",Session.sTechnicianId);
		fields.put("FConnect__Expense_Type__c",spType.getSelectedItem().toString());
		fields.put("FConnect__Amount__c",etAmount.getText().toString());  
		fields.put("FConnect__Discription__c", etDescription.getText().toString());
		fields.put("FConnect__Billable__c",flag);
		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(getString(R.string.api_version),objectType,fields);


			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {   
						progressDialog.dismiss();
						Log.i("TPT","Inserted");  
						etAmount.setText("");  
						etDescription.setText("");
						mBillable.setChecked(false);
						ExpensesMasterFragment newFragment3 = new ExpensesMasterFragment();
						Bundle args3 = new Bundle();
						args3.putInt("Position", position);
						newFragment3.setArguments(args3);
						FragmentTransaction transaction3 = getActivity().getSupportFragmentManager().beginTransaction();
						transaction3.replace(R.id.menus, newFragment3);                 
						transaction3.commit();
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}



	}

}
